/* eslint-disable */
import * as XLSX from "xlsx-js-style"
import jsPDF from 'jspdf'
import PizZip from 'pizzip';
import JSZip from 'jszip';
import JSZipUtils from 'jszip-utils'
import DocxTemplater from 'docxtemplater';
import { saveAs } from 'file-saver'
import axios from 'axios'
import "@/assets/fonts/FangZhengHeiTi-normal"//微软雅黑
import { fileSecretKey } from "@/views/formSystem/formDesign/config/formCmpConfig.js";

// 基础导出excel(header为key -> name 的映射,如{title:'标题'})
export function export2Excel(objectArray, headerProperties, fileName = '导出数据.xlsx') {
    const startTime = performance.now();
    // 创建一个新的工作簿
    let wb = XLSX.utils.book_new();
    // 创建一个新的工作表
    let headers = Object.keys(headerProperties);
    let headerNames = Object.values(headerProperties);
    let newData = objectArray.map(item => {
        let newItem = {};
        headers.forEach((header, index) => {
            newItem[headerNames[index]] = item[header];
        });
        console.log(newItem)
        return newItem;
    });
    var ws = XLSX.utils.json_to_sheet(newData, { header: headerNames });
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
    XLSX.writeFile(wb, fileName);
    const endTime = performance.now();
    const totalTime = endTime - startTime;
}
//含超链接导出(objectArray:对象数组,headerProperties:属性和表头映射关系，links:字符串数组,需要设置超链接的属性名)
export function export2ExcelWithLinks(objectArray, headerProperties, links, fileName = '导出数据.xlsx') {
    const startTime = performance.now();
    let wb = XLSX.utils.book_new();
    let headers = Object.keys(headerProperties);
    let headerNames = Object.values(headerProperties);
    let newData = objectArray.map(item => {
        let newItem = {};
        headers.forEach((header, index) => {
            const linkIndex = links.findIndex(link => header.includes(link));
            if (linkIndex !== -1) {
                const linkData = item[header];
                const linkText = linkData.map(link => `${link.fileName}\n${link.url}${fileSecretKey}`).join('\n');
                newItem[headerNames[index]] = {
                    v: linkText,
                    l: linkData.map(link => ({
                        Target: link.url,
                        Tooltip: link.fileName
                    }))
                };
            } else {
                newItem[headerNames[index]] = item[header];
            }
        });
        return newItem;
    });
    var ws = XLSX.utils.json_to_sheet(newData, { header: headerNames });
    //表格样式设置
    const wscols = headers.map(() => ({ wpx: 200 }));
    ws['!cols'] = wscols;
    const headerCellStyle = {
        fill: {
            fgColor: { rgb: "2980ba" },
        },
        font: {
            bold: true,
            sz: 16,
            color: { rgb: "FFFFFF" },
        },
    };
    headerNames.forEach((header, i) => {
        ws[XLSX.utils.encode_cell({ r: 0, c: i })].s = headerCellStyle;
    });
    // 添加超链接
    newData.forEach((item, rowIndex) => {
        links.forEach(link => {
            const linkIndex = headerNames.findIndex(header => header.includes(link));
            if (item[linkIndex]) {
                const cell = XLSX.utils.encode_cell({
                    r: rowIndex + 1,
                    c: linkIndex
                });
                const hyperlink = `Sheet1!${cell}`;
                ws[cell].l = item[linkIndex].l;
                ws[cell].t = 's';
                ws[cell].v = item[linkIndex].v;
                ws[cell].s = {
                    underline: true,
                    color: { rgb: '0, 100, 200' }
                };
                ws[cell].f = `HYPERLINK("${hyperlink}", "${item[linkIndex].v}")`;
            }
        });
    });

    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
    XLSX.writeFile(wb, fileName);
    const endTime = performance.now();
    const totalTime = endTime - startTime;
    console.log(`用时: ${totalTime} 毫秒`);
}



//导出pdf(objectArray:对象数组,headerProperties:属性和表头映射关系，imgData:图片base64文件，chunkSize:每页显示条数，显示不下自动换页)
export async function export2Pdf(objectArray, headerProperties, imgData, fileName = '导出数据.pdf', chunkSize = 99999) {
    const startTime = performance.now()
    const doc = new jsPDF();
    let startY = 20;
    doc.setFont("FangZhengHeiTi");

    if (Array.isArray(imgData) && imgData.length > 0) {
        for (let i = 0; i < imgData.length; i++) {
            const currentImgData = imgData[i];
            // 图片属性,宽度百分百，高度自适应
            const pageWidth = doc.internal.pageSize.getWidth();
            const imgWidth = pageWidth - 20;
            const img = new Image();
            img.src = currentImgData;
            await new Promise((resolve, reject) => {
                img.onload = resolve;
                img.onerror = reject;
            });
            let ratio = img.width / img.height;
            const imgHeight = imgWidth / ratio;
            // 添加图片
            doc.addImage(currentImgData, 'PNG', 10, startY, imgWidth, imgHeight);
            startY += imgHeight + 20;
        }
    }
    // 分割数组并添加第一页的表格内容
    addChunkToPDF(objectArray.slice(0, chunkSize), headerProperties, doc, startY);
    // doc.addPage();
    // 分割数组并添加后续页的表格内容
    for (let i = chunkSize; i < objectArray.length; i += chunkSize) {
        const chunk = objectArray.slice(i, i + chunkSize);
        addChunkToPDF(chunk, headerProperties, doc);
        if (i + chunkSize < objectArray.length) {
            doc.addPage();
        }
    }
    // 保存PDF
    const endTime = performance.now();
    doc.save(fileName);
    const totalTime = endTime - startTime;
    console.log(`用时: ${totalTime} 毫秒`);
}

function addChunkToPDF(chunk, headerProperties, doc, startY = 10) {
    const tableData = chunk.map(item => Object.keys(headerProperties).map(key => item[key]));
    const headerNames = Object.values(headerProperties);
    doc.autoTable({
        startY: startY,
        head: [headerNames],
        body: tableData,
        theme: 'striped',
        styles: {
            cellPadding: 1,
            font: 'FangZhengHeiTi',
            fontSize: 10,
            overflow: 'linebreak',
        },
    });
}

// 根据模板填充word
function generateDocxFile(fileData) {
    console.log(fileData, 777)
    return new Promise((resolve, reject) => {
        JSZipUtils.getBinaryContent('/hcs/doc/statisticsTemplate.docx', (err, content) => {
            if (err) {
                throw err;
            }
            const zip = new PizZip(content);
            const doc = new DocxTemplater()
                .loadZip(zip)
                .render(fileData);
            const out = doc.getZip().generate({
                type: 'blob',
                mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            });
            resolve(out);
        })
    });
}
//文件夹名称特殊字符替换
function sanitizeFolderName(name) {
    const regex = /[<>:"/\\|?*]/g;
    return name.toString().replace(regex, "");
}
//word批量打包导出
export async function exportWordZip(data, zipName) {
    const zip = new JSZip();
    for (const item of data) {
        const firstFolderName = sanitizeFolderName(item.phone+item.name)
        const folder = zip.folder(firstFolderName);
        const docxFile = await generateDocxFile(item);
        folder.file(`${item.phone}${item.name}.docx`, docxFile);
        //该问卷附件或图片上传，则创建files文件夹
        if (item.genFolder) {
            const subfolder = folder.folder('files');
            for (const questionAndResult of item.questionAndResult) {
                //遍历问题，为有附件的问题再建立子文件夹，以问题命名
                if (questionAndResult.hasFile) {
                    const thirdFolderName = sanitizeFolderName(questionAndResult.question);
                    const questionFolder = subfolder.folder(thirdFolderName);
                    //创建该问题的附件下载请求集合
                    const resultPromises = [];
                    for (const result of questionAndResult.result) {
                        const promise = axios.get(result.url, { responseType: 'blob' });
                        resultPromises.push(promise);
                    }
                    //发送请求，并将返回文件存到问题文件夹下
                    const fileResponses = await axios.all(resultPromises);
                    for (let i = 0; i < fileResponses.length; i++) {
                        const fileResponse = fileResponses[i];
                        // let suffix = fileTypes[fileResponse.headers['content-type']]
                        const result = questionAndResult.result[i];
                        const file = new File([fileResponse.data], result.fileName, { type: fileResponse.headers['content-type'] });
                        questionFolder.file(result.fileName, file);
                    }
                }
            }
        }
    }

    const zipFile = await zip.generateAsync({ type: "blob" });
    saveAs(zipFile, zipName + "统计数据.zip");
}
